<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px" class="three-column-form">
      <el-form-item label="管理单位" prop="orgId">
        <treeselect
          v-model="queryParams.orgId"
          :options="deptOptions"
          :normalizer="normalizer"
          :show-count="true"
          placeholder="请选择管理单位"
          @select="handleDeptSelect"
        />
      </el-form-item>
      <el-form-item label="电表编号" prop="meterNo">
        <el-input
          v-model="queryParams.meterNo"
          placeholder="请输入电表编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备类别" prop="sortCode">
        <el-select v-model="queryParams.sortCode" placeholder="请选择设备类别" clearable>
          <el-option
            v-for="dict in dict.type.meter_device"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['device:device:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['device:device:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['device:device:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['device:device:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div class="table-container">
      <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange" style="width: 100%">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column label="管理单位" align="center" prop="deptName" width="220" />
      <el-table-column label="电表编号" align="center" prop="meterNo" width="240">
        <template slot-scope="scope">
          <div class="meter-no-container">
            <el-tooltip v-if="scope.row.deviceStatus === '1'" content="离线" placement="top">
              <span class="status-icon">🔴</span>
            </el-tooltip>
            <el-tooltip v-else-if="scope.row.deviceStatus === '2'" content="在线/空闲" placement="top">
              <span class="status-icon">🟢</span>
            </el-tooltip>
            <el-tooltip v-else-if="scope.row.deviceStatus === '3'" content="使用中" placement="top">
              <span class="status-icon">🟡</span>
            </el-tooltip>
            <el-tooltip :content="scope.row.meterNo" placement="top">
              <span >{{ scope.row.meterNo }}</span>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>      
      <el-table-column label="设备类别" align="center" prop="sortCode" width="180">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.meter_device" :value="scope.row.sortCode"/>
        </template>
      </el-table-column>
      <el-table-column label="通讯规约" align="center" prop="commProtCode" width="150">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.up_protocol" :value="scope.row.commProtCode"/>
        </template>
      </el-table-column>
      <el-table-column label="通讯波特率" align="center" prop="baudrateCode" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.baudrate_code" :value="scope.row.baudrateCode"/>
        </template>
      </el-table-column>
      <el-table-column label="标定电压" align="center" prop="voltCode" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.volt_code" :value="scope.row.voltCode"/>
        </template>
      </el-table-column>
      <el-table-column label="标定电流" align="center" prop="ratedCurrent" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.rated_current" :value="scope.row.ratedCurrent"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="350" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-connection"
            @click="handleIotModule(scope.row)"
            :disabled="scope.row.deviceStatus === '1' || !scope.row.iotModuleId"
          >物联模块</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-data-line"
            @click="handlePowerData(scope.row)"
          >正向有功功率</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh"
            @click="handleResetIotModule(scope.row)"
            v-hasPermi="['device:device:edit']"
          >重置IoT模块</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['device:device:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['device:device:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
      </el-table>
    </div>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 物联网模块详情对话框 -->
    <el-dialog title="物联网模块详情" :visible.sync="iotDialogVisible" width="1000px" append-to-body :close-on-click-modal="false" custom-class="iot-detail-dialog">
      <div class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="ID">{{ iotViewForm.id }}</el-descriptions-item>
          <el-descriptions-item label="IMEI号">{{ iotViewForm.imei }}</el-descriptions-item>
          <el-descriptions-item label="固件版本号">{{ iotViewForm.fvn }}</el-descriptions-item>
          <el-descriptions-item label="硬件版本号">{{ iotViewForm.hv }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="iot-operations" style="margin: 20px 0; text-align: center;">
          <el-button
            type="primary"
            icon="el-icon-upload"
            @click="handleIotUpdateOTA"
            v-hasPermi="['device:iot:updateOTA']"
          >更新OTA</el-button>
          <el-button
            type="success"
            icon="el-icon-time"
            @click="handleIotSetTime"
            v-hasPermi="['device:iot:setTime']"
          >设置时间</el-button>
          <el-button
            type="warning"
            icon="el-icon-time"
            @click="handleIotSetHeartupTime"
            v-hasPermi="['device:iot:setHeartupTime']"
          >设置心跳时间</el-button>
          <el-button
            :type="newPwrSta === 0 ? 'success' : 'danger'"
            :icon="newPwrSta === 0 ? 'el-icon-open' : 'el-icon-turn-off'"
            @click="handleIotTogglePwrSta"
            v-hasPermi="['device:iot:setPwrSta']"
          >{{ newPwrSta === 0 ? '开启继电器' : '关闭继电器' }}</el-button>
        </div>
        
        <el-divider content-position="center">详细信息</el-divider>
        
        <el-tabs v-model="activeIotTab" type="border-card" @tab-click="handleIotTabClick" class="detail-tabs">
          <el-tab-pane label="心跳记录" name="heartbeat">
            <!-- 心跳记录查询条件 -->
            <el-form :model="iotHeartbeatQueryParams" ref="iotHeartbeatQueryForm" size="small" :inline="true" class="tab-query-form">
              <el-form-item label="开始时间" prop="startTime">
                <el-date-picker
                  v-model="iotHeartbeatQueryParams.startTime"
                  type="datetime"
                  placeholder="选择开始时间"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  style="width: 200px;"
                />
              </el-form-item>
              <el-form-item label="结束时间" prop="endTime">
                <el-date-picker
                  v-model="iotHeartbeatQueryParams.endTime"
                  type="datetime"
                  placeholder="选择结束时间"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  style="width: 200px;"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleIotHeartbeatQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetIotHeartbeatQuery">重置</el-button>
              </el-form-item>
            </el-form>
            
            <div class="table-container">
              <el-table v-loading="iotHeartbeatLoading" :data="iotHeartbeatList" height="300">
                <el-table-column type="index" width="50" label="序号" align="center" />
                <el-table-column label="心跳记录时间" prop="heartbeatTime" width="240" />
                <el-table-column label="ICCID卡号" prop="iccid" width="200" />
                <el-table-column label="4G信号强度" prop="dfs" width="150" />
                <el-table-column label="供电输出状态" prop="pwrSta" width="150" >
                  <template slot-scope="scope">
                    <el-tag v-if="scope.row.pwrSta === 0" type="default">关闭</el-tag>
                    <el-tag v-else type="success">开启</el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            
            <pagination
              v-show="iotHeartbeatTotal>0"
              :total="iotHeartbeatTotal"
              :page.sync="iotHeartbeatQueryParams.pageNum"
              :limit.sync="iotHeartbeatQueryParams.pageSize"
              @pagination="getIotHeartbeatList"
            />
          </el-tab-pane>
          
          <el-tab-pane label="操作日志" name="log">
            <!-- 操作日志查询条件 -->
            <el-form :model="iotLogQueryParams" ref="iotLogQueryForm" size="small" :inline="true" class="tab-query-form">
              <el-form-item label="开始时间" prop="startTime">
                <el-date-picker
                  v-model="iotLogQueryParams.startTime"
                  type="datetime"
                  placeholder="选择开始时间"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  style="width: 200px;"
                />
              </el-form-item>
              <el-form-item label="结束时间" prop="endTime">
                <el-date-picker
                  v-model="iotLogQueryParams.endTime"
                  type="datetime"
                  placeholder="选择结束时间"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  style="width: 200px;"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleIotLogQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetIotLogQuery">重置</el-button>
              </el-form-item>
            </el-form>
            
            <div class="table-container">
              <el-table v-loading="iotLogLoading" :data="iotLogList" height="300">
                <el-table-column type="index" width="50" label="序号" align="center" />
                <el-table-column label="操作时间" prop="opTime" width="180" />
                <el-table-column label="操作类型" prop="opType" width="120" >
                  <template slot-scope="scope">
                    <dict-tag :options="dict.type.iot_module_op" :value="scope.row.opType"/>
                  </template>
                </el-table-column>
                <el-table-column label="操作详情" prop="opData" />
              </el-table>
            </div>
            
            <pagination
              v-show="iotLogTotal>0"
              :total="iotLogTotal"
              :page.sync="iotLogQueryParams.pageNum"
              :limit.sync="iotLogQueryParams.pageSize"
              @pagination="getIotLogList"
            />
          </el-tab-pane>
          
          <el-tab-pane label="DLT698指令" name="dlt698">
            <!-- DLT698指令查询条件 -->
            <el-form :model="iotDlt698QueryParams" ref="iotDlt698QueryForm" size="small" :inline="true" class="tab-query-form">
              <el-form-item label="开始时间" prop="startTime">
                <el-date-picker
                  v-model="iotDlt698QueryParams.startTime"
                  type="datetime"
                  placeholder="选择开始时间"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  style="width: 200px;"
                />
              </el-form-item>
              <el-form-item label="结束时间" prop="endTime">
                <el-date-picker
                  v-model="iotDlt698QueryParams.endTime"
                  type="datetime"
                  placeholder="选择结束时间"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  style="width: 200px;"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleIotDlt698Query">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetIotDlt698Query">重置</el-button>
              </el-form-item>
            </el-form>
            
            <div class="table-container">
              <el-table v-loading="iotDlt698Loading" :data="iotDlt698List" height="300">
                <el-table-column type="index" width="50" label="序号" align="center" />
                <el-table-column label="发送/接收时间" prop="createTime" width="180" />
                <el-table-column label="指令类别" prop="msgType" width="120" >
                  <template slot-scope="scope">
                    <dict-tag :options="dict.type.dlt698_instruct" :value="scope.row.msgType"/>
                  </template>
                </el-table-column>
                <el-table-column label="指令详情" prop="msgData" />
              </el-table>
            </div>
            
            <pagination
              v-show="iotDlt698Total>0"
              :total="iotDlt698Total"
              :page.sync="iotDlt698QueryParams.pageNum"
              :limit.sync="iotDlt698QueryParams.pageSize"
              @pagination="getIotDlt698List"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>

    <!-- 正向有功功率数据对话框 -->
    <el-dialog title="正向有功功率数据" :visible.sync="powerDialogVisible" width="80%" append-to-body>
      <el-form :model="powerQueryParams" ref="powerQueryForm" size="small" :inline="true" label-width="68px">
        <el-form-item label="采集时间">
          <el-date-picker
            v-model="powerDaterangeCollectionTime"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handlePowerQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetPowerQuery">重置</el-button>
        </el-form-item>
      </el-form>
      
      <el-table v-loading="powerLoading" :data="powerList" style="width: 100%">
        <el-table-column type="index" width="50" label="序号" align="center" />
        <el-table-column label="电能表编号" align="center" prop="electricityMeterName" />
        <el-table-column label="采集时间" align="center" prop="collectionTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.collectionTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="有功功率" align="center" prop="activePower" />
      </el-table>
      
      <pagination
        v-show="powerTotal>0"
        :total="powerTotal"
        :page.sync="powerQueryParams.pageNum"
        :limit.sync="powerQueryParams.pageSize"
        @pagination="getPowerList"
      />
    </el-dialog>

    <!-- 添加或修改电能表管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="dialog-form">
        <el-form-item label="管理单位" prop="orgId">
          <treeselect
            v-model="form.orgId"
            :options="deptOptions"
            :normalizer="normalizer"
            placeholder="请选择管理单位"
            @select="handleFormDeptSelect"
          />
        </el-form-item>
        
        <el-form-item label="生产厂家" prop="manufacturer">
          <el-select v-model="form.manufacturer" placeholder="请选择生产厂家">
            <el-option
              v-for="dict in dict.type.manufacturer"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电表编号" prop="meterNo">
          <el-input v-model="form.meterNo" placeholder="请输入电表编号" />
        </el-form-item>
        <el-form-item label="表地址码" prop="logicAddr">
          <el-input v-model="form.logicAddr" placeholder="请输入表地址码" />
        </el-form-item>
        <el-form-item label="设备类别" prop="sortCode">
          <el-select v-model="form.sortCode" placeholder="请选择设备类别">
            <el-option
              v-for="dict in dict.type.meter_device"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备类型" prop="typeCode">
          <el-select v-model="form.typeCode" placeholder="请选择设备类型">
            <el-option
              v-for="dict in dict.type.meter_device_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="接线方式" prop="wiringMode">
          <el-select v-model="form.wiringMode" placeholder="请选择接线方式">
            <el-option
              v-for="dict in dict.type.wiring_mode"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="通讯规约" prop="commProtCode">
          <el-select v-model="form.commProtCode" placeholder="请选择通讯规约">
            <el-option
              v-for="dict in dict.type.up_protocol"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="通讯波特率" prop="baudrateCode">
          <el-select v-model="form.baudrateCode" placeholder="请选择通讯波特率">
            <el-option
              v-for="dict in dict.type.baudrate_code"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="通讯方式" prop="commModeCode">
          <el-select v-model="form.commModeCode" placeholder="请选择通讯方式">
            <el-option
              v-for="dict in dict.type.up_channel"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="综合倍率" prop="tFactor">
          <el-input v-model="form.tFactor" placeholder="请输入综合倍率" />
        </el-form-item>
        <el-form-item label="标准电压(V)" prop="voltCode">
          <el-select v-model="form.voltCode" placeholder="请选择标准电压(V)">
            <el-option
              v-for="dict in dict.type.volt_code"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标准电流(A)" prop="ratedCurrent">
          <el-select v-model="form.ratedCurrent" placeholder="请选择标准电流(A)">
            <el-option
              v-for="dict in dict.type.rated_current"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电价码" prop="prcCode">
          <el-select v-model="form.prcCode" placeholder="请选择电价码">
            <el-option
              v-for="item in prcCodeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
              <span>{{ item.label }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用电容量" prop="powerCapacity">
          <el-input v-model="form.powerCapacity" placeholder="请输入用电容量" />
        </el-form-item>
        <el-form-item label="用户编号" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户编号" />
        </el-form-item>
        <el-form-item label="用户户号" prop="consNo">
          <el-input v-model="form.consNo" placeholder="请输入用户户号" />
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="用户地址" prop="userAddr">
          <el-input v-model="form.userAddr" placeholder="请输入用户地址" />
        </el-form-item>
        <el-divider content-position="left"></el-divider>
        <el-form-item label="共享用电点" prop="powerId">
          <el-select
            v-model="form.powerId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入用电点编号或名称"
            :remote-method="remoteSearch"
            :loading="powerPointLoading"
            @change="handlePowerPointChange"
            @focus="remoteSearch"
          >
            <el-option
              v-for="item in powerPointOptions"
              :key="item.id"
              :label="item.powerName + '(' + item.powerNo + ')'"
              :value="item.id"
            >
              <span>{{ item.powerName }}({{ item.powerNo }})</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分路号" prop="channelNo">
          <el-select 
            v-model="form.channelNo" 
            placeholder="请选择分路号" 
            :disabled="!form.powerPointInfo"
          >
            <el-option
              v-for="n in channelOptions"
              :key="n"
              :label="n"
              :value="n.toString()"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="白码值" prop="qrcode">
          <el-input v-model="form.qrcode" placeholder="请输入白码值" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
/* 对话框表单样式 */
.dialog-form {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -10px;
}

.dialog-form .el-form-item {
  width: calc(50% - 20px);
  margin: 0 10px 10px;
  box-sizing: border-box;
}

.dialog-form .el-form-item .el-form-item__content {
  width: calc(100% - 120px) !important;
}

/* 输入框和选择框样式 */
.dialog-form .el-form-item .el-input,
.dialog-form .el-form-item .el-select,
.dialog-form .el-form-item .el-date-editor {
  width: 100% !important;
}

.dialog-form .el-form-item .el-input__inner,
.dialog-form .el-form-item .el-select .el-input__inner,
.dialog-form .el-form-item .el-date-editor .el-input__inner {
  width: 100% !important;
}

/* select组件样式 */
.dialog-form .el-form-item .el-select .el-input {
  width: 100% !important;
}

/* 日期组件样式 */
.dialog-form .el-form-item .el-date-editor {
  width: 100% !important;
}

/* 搜索表单样式保持不变 */
.three-column-form .el-form-item .el-form-item__content {
  width: calc(100% - 145px) !important;
}

.three-column-form .el-form-item .el-select {
  width: 100% !important;
}

.three-column-form .el-form-item .el-select .el-input {
  width: 100% !important;
}

.three-column-form .el-form-item .el-select .el-input__inner {
  width: 100% !important;
}

.three-column-form .el-form-item .el-date-editor {
  width: 100% !important;
}

.three-column-form .el-form-item .el-date-editor .el-input__inner {
  width: 100% !important;
}

.three-column-form .el-form-item:last-child .el-form-item__content {
  width: 100% !important;
  margin-left: 0;
  text-align: right;
}

.three-column-form .el-form-item:last-child .el-button {
  margin-left: 10px;
}

/* 添加树形选择器样式 */
.three-column-form .vue-treeselect {
  width: 100%;
}

.three-column-form .vue-treeselect .vue-treeselect__control {
  border-radius: 4px;
}

/* 对话框表单中的树形选择器样式 */
.dialog-form .vue-treeselect {
  width: 100%;
}

.dialog-form .vue-treeselect .vue-treeselect__control {
  border-radius: 4px;
}

/* 逻辑地址输入框样式 */
.logic-address-item .el-form-item__content {
  width: calc(100% - 120px) !important;
}

.logic-address-inputs {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.logic-address-inputs .el-input {
  width: 48% !important;
}

.logic-address-inputs .el-input__inner {
  width: 100% !important;
}

/* 表格容器样式 */
.table-container {
  width: 100%;
  overflow-x: auto;
  overflow-y: hidden;
}

.table-container .el-table {
  min-width: 100%;
  width: auto;
}

/* 确保表格内容不会被压缩 */
.table-container .el-table__body-wrapper {
  overflow-x: auto;
  overflow-y: hidden;
}

.table-container .el-table__header-wrapper {
  overflow-x: auto;
  overflow-y: hidden;
}

/* 电表编号容器样式 */
.meter-no-container {
  display: flex;
  align-items: center;
  justify-content: center;
  white-space: nowrap;
}

/* 状态图标样式 */
.status-icon {
  margin-right: 4px;
  flex-shrink: 0;
}

/* 电表编号文本省略样式 */
.meter-no-text {
  display: inline-block;
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}

/* 物联网模块详情对话框样式 */
.iot-detail-dialog .detail-content {
  padding: 20px 0;
}

.iot-detail-dialog .detail-tabs {
  margin-top: 20px;
}

.iot-detail-dialog .tab-query-form {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.iot-detail-dialog .table-container {
  margin-bottom: 20px;
}

.iot-detail-dialog .iot-operations {
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.iot-detail-dialog .iot-operations .el-button {
  margin: 0 8px;
}

/* 固定列样式 */
.table-container .el-table__fixed-right {
  height: 100% !important;
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.15);
}

.table-container .el-table__fixed {
  height: 100% !important;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.15);
}
</style>

<style scoped>
.three-column-form {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -10px;
}

.three-column-form .el-form-item {
  width: calc(33.33% - 20px);
  margin: 0 10px 10px;
  box-sizing: border-box;
}

.three-column-form .el-form-item:last-child {
  width: 100%;
  margin: 0 10px;
  text-align: right;
}

/* 用电点选择器样式 */
.el-select-dropdown__item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>

<script>
import { listDevice, getDevice, delDevice, addDevice, updateDevice, resetIotModule } from "@/api/device/device"
import { listPower } from "@/api/device/power"
import { getIot, updateOTA, setTime, setHeartupTime, setPwrSta, heartbeat } from "@/api/device/iot"
import { listLog } from "@/api/device/log"
import { listLog as listDlt698Log } from "@/api/iot/log"
import { listDept } from "@/api/system/dept"
import { listStation } from "@/api/station/station"
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
import { listConfig } from "@/api/config/config"

export default {
  name: "Device",
  components: { Treeselect },
  dicts: ['up_channel', 'volt_code', 'rated_current', 'baudrate_code', 'meter_device', 'meter_device_type', 'wiring_mode', 'manufacturer', 'up_protocol', 'elec_type_code', 'elec_type_code1', 'channel_code', 'iot_module_op', 'dlt698_instruct'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 电能表管理表格数据
      deviceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orgId: null,
        meterNo: null,
        logicAddr: null,
        sortCode: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orgId: [
          { required: true, message: "管理单位不能为空", trigger: "blur" }
        ],
        meterNo: [
          { required: true, message: "电表编号不能为空", trigger: "blur" }
        ],
        logicAddr: [
          { required: true, message: "表地址码不能为空", trigger: "blur" }
        ],
        sortCode: [
          { required: true, message: "设备类别不能为空", trigger: "change" }
        ],
        typeCode: [
          { required: true, message: "设备类型不能为空", trigger: "change" }
        ],
        wiringMode: [
          { required: true, message: "接线方式不能为空", trigger: "change" }
        ],
        commProtCode: [
          { required: true, message: "通讯规约不能为空", trigger: "change" }
        ],
        baudrateCode: [
          { required: true, message: "通讯波特率不能为空", trigger: "change" }
        ],
        commModeCode: [
          { required: true, message: "通讯方式不能为空", trigger: "change" }
        ],
        tFactor: [
          { required: true, message: "综合倍率不能为空", trigger: "blur" }
        ],
        voltCode: [
          { required: true, message: "标准电压不能为空", trigger: "change" }
        ],
        ratedCurrent: [
          { required: true, message: "标准电流不能为空", trigger: "change" }
        ],
        prcCode: [
          { required: true, message: "电价码不能为空", trigger: "blur" }
        ],
        consNo: [
          { required: true, message: "用户户号不能为空", trigger: "blur" }
        ],
        powerId: [
          { required: true, message: "共享用电点不能为空", trigger: "blur" }
        ],
        channelNo: [
          { required: true, message: "分路号不能为空", trigger: "blur" }
        ],
        qrcode: [
          { required: true, message: "白码值不能为空", trigger: "blur" }
        ]
      },
      // 部门树选项
      deptOptions: [],
      // 用电点列表
      powerPointOptions: [],
      // 所有用电点数据
      allPowerPoints: [],
      // 用电点加载状态
      powerPointLoading: false,
      // 分路号选项
      channelOptions: [],
      // 电价配置列表
      prcCodeOptions: [],
      // 功率数据对话框相关
      powerDialogVisible: false,
      powerLoading: false,
      powerList: [],
      powerTotal: 0,
      powerDaterangeCollectionTime: [],
      powerQueryParams: {
        pageNum: 1,
        pageSize: 10,
        collectionTime: null,
        electricityMeterId: null
      },
      currentDeviceId: null,
      // 物联网模块相关
      iotDialogVisible: false,
      iotViewForm: {},
      activeIotTab: 'heartbeat',
      // 心跳记录相关
      iotHeartbeatLoading: false,
      iotHeartbeatList: [],
      iotHeartbeatTotal: 0,
      iotHeartbeatQueryParams: {
        pageNum: 1,
        pageSize: 10,
        iotModuleId: null,
        startTime: null,
        endTime: null
      },
      // 操作日志相关
      iotLogLoading: false,
      iotLogList: [],
      iotLogTotal: 0,
      iotLogQueryParams: {
        pageNum: 1,
        pageSize: 10,
        iotModuleId: null,
        startTime: null,
        endTime: null
      },
      // DLT698指令相关
      iotDlt698Loading: false,
      iotDlt698List: [],
      iotDlt698Total: 0,
      iotDlt698QueryParams: {
        pageNum: 1,
        pageSize: 10,
        iotModuleId: null,
        startTime: null,
        endTime: null
      },
      // 开关状态
      newPwrSta: 0
    }
  },
  created() {
    this.getList()
    this.getDeptTree()
    this.getPrcCodeList()
    this.getAllPowerPoints()
  },
  methods: {
    /** 查询部门下拉树结构 */
    getDeptTree() {
      listDept().then(response => {
        this.deptOptions = this.handleTree(response.data, "deptId")
      })
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      }
    },
    /** 查询电能表管理列表 */
    getList() {
      this.loading = true
      listDevice(this.queryParams).then(response => {
        this.deviceList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 重置IoT模块
    handleResetIotModule(row) {
      resetIotModule(row.id).then(response => {
        this.$message.success("重置IoT模块成功")
        this.getList()
      })
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orgId: null,
        powerId: null,
        manufacturer: null,
        meterNo: null,
        logicAddr: null,
        sortCode: null,
        typeCode: null,
        wiringMode: null,
        commProtCode: null,
        baudrateCode: null,
        commModeCode: null,
        createTime: null,
        updateTime: null,
        tFactor: null,
        voltCode: null,
        ratedCurrent: null,
        prcCode: null,
        powerCapacity: null,
        userId: null,
        consNo: null,
        userName: null,
        userAddr: null,
        tgNo: null,
        channelNo: null,
        qrcode: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加电能表管理"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getDevice(id).then(response => {
        this.form = response.data
        // 如果有用电点信息，生成分路号选项
        if (this.form.powerPointInfo && this.form.powerPointInfo.maxChannels) {
          this.generateChannelOptions(this.form.powerPointInfo.maxChannels)
        }
        // 确保当前用电点信息在选项中
        if (this.form.powerPointInfo && !this.powerPointOptions.some(item => item.id === this.form.powerId)) {
          this.powerPointOptions.unshift({
            id: this.form.powerId,
            powerName: this.form.powerPointInfo.powerName,
            powerNo: this.form.powerPointInfo.powerNo
          })
        }
        // 确保当前电价码信息在选项中
        if (this.form.prcCode) {
          // 先检查是否已经在选项中
          const existingOption = this.prcCodeOptions.find(item => item.value === this.form.prcCode)
          if (!existingOption) {
            // 如果不在选项中，从后端获取详细信息
            listConfig({
              pageNum: 1,
              pageSize: 1,
              id: this.form.prcCode
            }).then(response => {
              if (response.rows && response.rows.length > 0) {
                const item = response.rows[0]
                const elecTypeLabel = this.selectDictLabel(this.dict.type.elec_type_code, item.elecTypeCode)
                const elecType1Label = this.selectDictLabel(this.dict.type.elec_type_code1, item.elecTypeCode1)
                const channelLabel = this.selectDictLabel(this.dict.type.channel_code, item.channelCode)
                const label = `${item.prcCode}(${elecTypeLabel},${elecType1Label}:${item.electricityExecTimeList[0].price}元，渠道编码:${item.channelCode})`
                // 检查是否已存在相同ID的选项
                const index = this.prcCodeOptions.findIndex(option => option.value === item.id)
                if (index === -1) {
                  // 如果不存在，添加到列表开头
                  this.prcCodeOptions.unshift({
                    value: item.id,
                    label: label,
                    raw: item
                  })
                } else {
                  // 如果已存在，更新该选项
                  this.prcCodeOptions[index] = {
                    value: item.id,
                    label: label,
                    raw: item
                  }
                }
                // 强制更新选择器的显示
                this.$nextTick(() => {
                  this.form.prcCode = item.id
                })
              }
            })
          } else {
            // 如果已在选项中，强制更新选择器的显示
            this.$nextTick(() => {
              this.form.prcCode = this.form.prcCode
            })
          }
        }
        this.open = true
        this.title = "修改电能表管理"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDevice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addDevice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除电能表管理编号为"' + ids + '"的数据项？').then(function() {
        return delDevice(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('device/device/export', {
        ...this.queryParams
      }, `device_${new Date().getTime()}.xlsx`)
    },
    /** 部门选择事件 */
    handleDeptSelect(node) {
      this.queryParams.orgId = node.id
      this.queryParams.orgName = node.label
    },
    handleFormDeptSelect(node) {
      this.formDeptName = node.label
    },
    /** 获取所有用电点数据 */
    getAllPowerPoints() {
      this.powerPointLoading = true
      listStation({
        pageNum: 1,
        pageSize: 1000
      }).then(response => {
        this.allPowerPoints = response.rows
        this.powerPointOptions = this.allPowerPoints
        this.powerPointLoading = false
      })
    },
    /** 用电点搜索 */
    remoteSearch(query) {
      if (query) {
        const searchText = query.toLowerCase()
        this.powerPointOptions = this.allPowerPoints.filter(item => 
          item.powerName.toLowerCase().includes(searchText) || 
          item.powerNo.toLowerCase().includes(searchText)
        )
      } else {
        this.powerPointOptions = this.allPowerPoints
      }
    },
    /** 用电点选择改变事件 */
    handlePowerPointChange(value) {
      const selectedPowerPoint = this.powerPointOptions.find(item => item.id === value)
      if (selectedPowerPoint) {
        this.form.powerPointInfo = selectedPowerPoint
        if (selectedPowerPoint.maxChannels) {
          this.generateChannelOptions(selectedPowerPoint.maxChannels)
        }
      }
    },
    /** 生成分路号选项 */
    generateChannelOptions(maxChannels) {
      this.channelOptions = Array.from({length: maxChannels}, (_, i) => i + 1)
    },
    /** 获取电价配置列表 */
    getPrcCodeList() {
      listConfig().then(response => {
        // 使用Map来去重，以value为key
        const uniqueMap = new Map()
        response.rows.forEach(item => {
          const elecTypeLabel = this.selectDictLabel(this.dict.type.elec_type_code, item.elecTypeCode)
          const elecType1Label = this.selectDictLabel(this.dict.type.elec_type_code1, item.elecTypeCode1)
          const channelLabel = this.selectDictLabel(this.dict.type.channel_code, item.channelCode)
          const label = `${item.prcCode}(${elecTypeLabel},${elecType1Label}:${item.electricityExecTimeList[0].price}元，渠道编码:${item.channelCode})`
          uniqueMap.set(item.id, {
            value: item.id,
            label: label,
            raw: item
          })
        })
        this.prcCodeOptions = Array.from(uniqueMap.values())
        // 如果当前正在编辑，确保电价码显示正确
        if (this.form.prcCode) {
          this.$nextTick(() => {
            this.form.prcCode = this.form.prcCode
          })
        }
      })
    },
    /** 查看正向有功功率数据 */
    handlePowerData(row) {
      this.currentDeviceId = row.id
      this.powerQueryParams.electricityMeterId = row.id
      this.powerDialogVisible = true
      this.getPowerList()
    },
    /** 查询功率数据列表 */
    getPowerList() {
      this.powerLoading = true
      this.powerQueryParams.params = {}
      if (null != this.powerDaterangeCollectionTime && '' != this.powerDaterangeCollectionTime) {
        this.powerQueryParams.params["beginCollectionTime"] = this.powerDaterangeCollectionTime[0]
        this.powerQueryParams.params["endCollectionTime"] = this.powerDaterangeCollectionTime[1]
      }
      listPower(this.powerQueryParams).then(response => {
        this.powerList = response.rows
        this.powerTotal = response.total
        this.powerLoading = false
      })
    },
    /** 功率数据搜索按钮操作 */
    handlePowerQuery() {
      this.powerQueryParams.pageNum = 1
      this.getPowerList()
    },
    /** 功率数据重置按钮操作 */
    resetPowerQuery() {
      this.powerDaterangeCollectionTime = []
      this.resetForm("powerQueryForm")
      this.handlePowerQuery()
    },
    /** 查看物联网模块详情 */
    handleIotModule(row) {
      this.iotDialogVisible = true
      this.activeIotTab = 'heartbeat'
      // 获取物联网模块详情
      getIot(row.iotModuleId).then(response => {
        this.iotViewForm = response.data
        // 设置查询参数中的iotModuleId
        this.iotHeartbeatQueryParams.iotModuleId = row.iotModuleId
        this.iotLogQueryParams.iotModuleId = row.iotModuleId
        this.iotDlt698QueryParams.iotModuleId = row.iotModuleId
        // 获取心跳记录
        this.getIotHeartbeatList()
      })
    },
    /** 关闭物联网模块对话框 */
    closeIotDialog() {
      this.iotDialogVisible = false
      this.iotViewForm = {}
      this.iotHeartbeatList = []
      this.iotLogList = []
      this.iotDlt698List = []
    },
    /** 物联网模块标签页切换 */
    handleIotTabClick(tab) {
      if (tab.name === 'heartbeat') {
        this.getIotHeartbeatList()
      } else if (tab.name === 'log') {
        this.getIotLogList()
      } else if (tab.name === 'dlt698') {
        this.getIotDlt698List()
      }
    },
    /** 查询心跳记录列表 */
    getIotHeartbeatList() {
      if (!this.iotHeartbeatQueryParams.iotModuleId) return

      this.iotHeartbeatLoading = true
      const params = {
        ...this.iotHeartbeatQueryParams,
        params: {}
      }
      if (this.iotHeartbeatQueryParams.startTime) {
        params.params.startTime = this.iotHeartbeatQueryParams.startTime
      }
      if (this.iotHeartbeatQueryParams.endTime) {
        params.params.endTime = this.iotHeartbeatQueryParams.endTime
      }
      
      heartbeat(params).then(response => {
        this.iotHeartbeatList = response.rows || response.data || []
        this.iotHeartbeatTotal = response.total || 0
        this.iotHeartbeatLoading = false
      }).catch(() => {
        this.iotHeartbeatLoading = false
      })
    },
    /** 心跳记录搜索 */
    handleIotHeartbeatQuery() {
      this.iotHeartbeatQueryParams.pageNum = 1
      this.getIotHeartbeatList()
    },
    /** 心跳记录重置 */
    resetIotHeartbeatQuery() {
      this.iotHeartbeatQueryParams.startTime = null
      this.iotHeartbeatQueryParams.endTime = null
      this.resetForm("iotHeartbeatQueryForm")
      this.handleIotHeartbeatQuery()
    },
    /** 查询操作日志列表 */
    getIotLogList() {
      if (!this.iotLogQueryParams.iotModuleId) return
      
      this.iotLogLoading = true
      const params = {
        ...this.iotLogQueryParams,
        params: {}
      }
      if (this.iotLogQueryParams.startTime) {
        params.params.startTime = this.iotLogQueryParams.startTime
      }
      if (this.iotLogQueryParams.endTime) {
        params.params.endTime = this.iotLogQueryParams.endTime
      }
      listLog(params).then(response => {
        this.iotLogList = response.rows
        this.iotLogTotal = response.total
        this.iotLogLoading = false
      }).catch(() => {
        this.iotLogLoading = false
      })
    },
    /** 操作日志搜索 */
    handleIotLogQuery() {
      this.iotLogQueryParams.pageNum = 1
      this.getIotLogList()
    },
    /** 操作日志重置 */
    resetIotLogQuery() {
      this.iotLogQueryParams.startTime = null
      this.iotLogQueryParams.endTime = null
      this.resetForm("iotLogQueryForm")
      this.handleIotLogQuery()
    },
    /** 查询DLT698指令列表 */
    getIotDlt698List() {
      if (!this.iotDlt698QueryParams.iotModuleId) return
      
      this.iotDlt698Loading = true
      const params = {
        ...this.iotDlt698QueryParams,
        params: {}
      }
      
      if (this.iotDlt698QueryParams.startTime) {
        params.params.startTime = this.iotDlt698QueryParams.startTime
      }
      if (this.iotDlt698QueryParams.endTime) {
        params.params.endTime = this.iotDlt698QueryParams.endTime
      }
      
      listDlt698Log(params).then(response => {
        this.iotDlt698List = response.rows
        this.iotDlt698Total = response.total
        this.iotDlt698Loading = false
      }).catch(() => {
        this.iotDlt698Loading = false
      })
    },
    /** DLT698指令搜索 */
    handleIotDlt698Query() {
      this.iotDlt698QueryParams.pageNum = 1
      this.getIotDlt698List()
    },
    /** DLT698指令重置 */
    resetIotDlt698Query() {
      this.iotDlt698QueryParams.startTime = null
      this.iotDlt698QueryParams.endTime = null
      this.resetForm("iotDlt698QueryForm")
      this.handleIotDlt698Query()
    },
    /** 更新OTA */
    handleIotUpdateOTA() {
      this.$modal.confirm('是否确认更新OTA？').then(() => {
        return updateOTA(this.iotViewForm.imei)
      }).then(() => {
        this.$modal.msgSuccess("OTA更新指令发送成功")
      }).catch(() => {})
    },
    /** 设置时间 */
    handleIotSetTime() {
      this.$modal.confirm('是否确认设置时间？').then(() => {
        return setTime(this.iotViewForm.imei)
      }).then(() => {
        this.$modal.msgSuccess("时间设置指令发送成功")
      }).catch(() => {})
    },
    /** 设置心跳时间 */
    handleIotSetHeartupTime() {
      this.$prompt('请输入心跳超时时间（秒）', '设置心跳时间', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^\d+$/,
        inputErrorMessage: '请输入有效的数字'
      }).then(({ value }) => {
        return setHeartupTime(this.iotViewForm.imei, value)
      }).then(() => {
        this.$modal.msgSuccess("心跳时间设置指令发送成功")
      }).catch(() => {})
    },
    /** 切换开关状态 */
    handleIotTogglePwrSta() {
      const action = this.newPwrSta === 0 ? '开启' : '关闭'
      this.$modal.confirm(`是否确认${action}设备？`).then(() => {
        return setPwrSta(this.iotViewForm.imei, this.newPwrSta ===0 ? 1:0)
      }).then(() => {
        this.$modal.msgSuccess(`${action}指令发送成功`)
        // 切换状态
        this.newPwrSta = this.newPwrSta === 0 ? 1 : 0
      }).catch(() => {})
    }
  }
}
</script>
